<?php
public function send_msg(){
		$this->load->library('session');
		$msg=$this->input->post('txtusermsg');
		$data = array_filter(explode('_',$this->input->post('data')));
		if($msg!='' && count($data)==2){
				$this->load->database();
				$reciverId = $data[1];
				$myuid = $data[0];
				$getthread = $this->db->query("select * from tbl_message_thread where (`sender_id`='$myuid' and `receiver_id`='$reciverId') or  (`sender_id`='$reciverId' and `receiver_id`='$myuid')");
				
				$threadArray = $getthread->result();
				if(count($threadArray)==0){
					$threadId = unique();
					$data = array(
					'thread_id'=>$threadId,
					'sender_id' => $myuid ,
					'receiver_id'=>$reciverId,
					'created_time' => date('Y-m-d H:i:s')
					);
					$c = $this->db->insert('tbl_message_thread', $data);//Creating thread
				}else{
					 $threadId = $threadArray[0]->thread_id;//if already created
				}
				if($threadId!=''){
					$data = array(
						'msg_id'=>unique(),
						'thread_id' => $threadId ,
						'sender_id' => $myuid ,
						'message'=>$msg,
						'created_date' => date('Y-m-d H:i:s')
						);
					$c = $this->db->insert('tbl_message', $data);
					
					if($c){$code = 200;}else{$code = 201;}
				}else{$code = 201;}
		}else{$code = 202;}
		switch($code){
		case 200: 
		$result = array('status'=>'200','msg'=>'<div class="alert alert-success">Your message Sucessfully.</div>');
		break;
		case 201: 
		$result = array('status'=>'201','msg'=>'<div class="alert alert-error">Your message is not sent.Try again!</div>');
		break;
		case 202:	
		$result = array('status'=>'201','msg'=>'<div class="alert alert-error">Message cannot be empty.Try again!</div>');
		break;
		
		}
		 header('Content-Type: application/json; charset=utf-8');
		echo json_encode($result, JSON_HEX_QUOT | JSON_HEX_TAG);
		exit();
	}
	public function send_chatmsg(){
		$newmsg=$this->input->post('newmsg');
		$threadId=$this->input->post('thread');
		$fid=$this->input->post('fid');//friend ID || reciver ID
		$lastime=$this->input->post('lastime');
		$lastmsgid=$this->input->post('lastmsgid');
		if($threadId!='' && $newmsg!='' && $lastime !='und' && $fid!=''&&$lastmsgid!='und'){
			$msgResponse = $this->send_messagetoReciver($newmsg,$fid,$threadId,$lastime);
			if($msgResponse){
				//echo json_encode(array("status"=>'200','response'=>$msgResponse,'remove_li'=>'yes'));
				echo json_encode(array("status"=>'200','response'=>"message send",'remove_li'=>'yes'));
			}else{ echo json_encode(array("status"=>'203','msg'=>'No recent message available.')); }
		}else{
			echo json_encode(array("status"=>'204','msg'=>'Message cannot be blank.'));
		}
		
		
	}
	private function send_messagetoReciver($newmsg,$reciverId,$threadId,$lastime){
		$this->load->database();
		$this->load->library('session');
		$myuid = $this->session->userdata("user_data");
		$myuid=$myuid['uid'];
		//$getthread = $this->db->query("SELECT `thread_id` FROM (`tbl_message_thread`) WHERE `thread_id` =  '$threadId' AND (`sender_id` =  '$myuid' OR `receiver_id` =  '$reciverId') and (`sender_id` =  '$reciverId' OR `receiver_id` =  '$myuid')");
						/* ->where(array("thread_id"=>$threadId,"sender_id"=>$myuid,"sender_id"=>$reciverId))
						 ->or_where(array("thread_id"=>$threadId,"sender_id"=>$reciverId,"sender_id"=>$myuid))
						 ->get("tbl_message_threads");*/
		//if($getthread->num_rows()>0){
			//$threadArray = $getthread->result();
			$data = array(
						'msg_id'=>unique(),
						'thread_id' => $threadId,
						'sender_id' => $myuid ,
						'message'=>$newmsg,
						'created_date' => date('Y-m-d H:i:s')
						);
			$c = $this->db->insert('tbl_message', $data);
			if($c){
				$getthread = $this->db->select("*,UNIX_TIMESTAMP(created_date) as msgtime")
						 ->where(array("thread_id"=>$threadId,"UNIX_TIMESTAMP(created_date) > "=>$lastime))
						 ->get("tbl_message");
				if($getthread->num_rows()>0){
					return $getthread->result_array();
				}else{ return $getthread->num_rows();}
			}else{  return false; }
		//}else{  return false; }
	
	}
	
	public function get_messages(){
		$threadid = $this->input->post('thread');
		$usersid = $this->input->post('userssid');
		if($threadid != ''){
			$this->load->model("message_model");
			$messages = $this->message_model->show_thread_messages($threadid,$usersid);
			if($messages!=0){
				foreach($messages as $rows)
				{
					$rows['timeago'] = time_passed($rows['created_date']);
					$data[] = $rows;
				}
				echo json_encode(array('status'=>'200','response'=>$data));
			}else{
				echo json_encode(array('status'=>'201','msg'=>'No Conversation'));
			}
		}else{echo json_encode(array('status'=>'202','msg'=>'No conversation'));}
	}
	
	/*function send_msg(){
		$this->load->library('session');
		$msg=$this->input->post('txtusermsg');
		if($msg!=''){
		$this->load->database();
		$this->load->library('session');
		$id = $this->session->userdata("mymodid");
		$uid = $this->session->userdata("user_data");
		$uid=$uid['uid'];
		$data = array(
		'sent_by'=>$uid,
		'sent_to' => $id ,
		'message'=>$msg,
   		'sent_on' => date('Y-m-d H:i:s')
		);
		$c = $this->db->insert('tbl_messages', $data);
		echo json_encode(array('status'=>'200','msg'=>'<div class="alert alert-success">your message Sucessfully.</div>'));
		}else{
			echo json_encode(array('status'=>'201','msg'=>'<div class="alert alert-error">your message is not sent.Try again!</div>'));
		}
		
	}*/
	
	function read_msg(){
		if($this->input->is_ajax_request()){
			$uid = $this->session->userdata("user_data");
			$uid=$uid['uid'];
			$thread = $this->input->post("thread");
			$senderid = $this->input->post("id");
			
			//$this->db->where(array('thread_id'=>$thread,'sender_id'=>$senderid));
			//$c = $this->db->update('tbl_message',array('flag_seen'=>'1','seen_on'=>now()));
			$this->db->query("UPDATE `tbl_message` SET `flag_seen` = '1', `seen_on` = now() WHERE `thread_id` = '$thread' AND `sender_id` =  '$senderid'");
			
			echo json_encode(array("status"=>200,"result"=>array("thread"=>$thread)));
			
		}else{
			echo json_encode(array("status"=>501,"result"=>"This request not processed."));
		}
	}
	public function newmsgpull(){
	if($this->input->is_ajax_request()){
		$thread = $this->input->post('thread');
		$msgid = $this->input->post('msgid');
		$lastmsgtime =$this->input->post('lastmsgtime');
		$userid =$this->input->post('userid');
		$msgcheck = $this->db->query("select m.created_date as msgtime, m.msg_id as msg_id, m.message, r.first_name, r.last_name, r.profile_pic_id from tbl_message m inner join tbl_user_registration r on r.id= m.sender_id where UNIX_TIMESTAMP(m.`created_date`)>'".$lastmsgtime."' and m.`thread_id` ='$thread' and m.delete_status<>'1' and m.delete_status<>'$userid' ");
		$userid = $this->uid["uid"];
		$this->db->query("UPDATE `tbl_message` SET `flag_seen` = '1', `seen_on` = now() WHERE `thread_id` = '$thread' AND `sender_id` <>  '$userid'");
		if($msgcheck->num_rows()>0){
			foreach($msgcheck->result_array() as $rows)
			{
				$rows['timeago'] = time_passed($rows['msgtime']);
				$rows['msgtime'] = strtotime($rows['msgtime']);
				$rows['sender_pic'] = base_url()."image_controller/get_thumbs/".$rows['profile_pic_id'];
				$data[] = $rows;
			}
		
			echo json_encode(array('status'=>200,'result'=>$data,'thread'=>$thread));
		}else{echo json_encode(array('status'=>201,'result'=>"No new message."));}
	}else{
		echo json_encode(array("status"=>501,"result"=>"This request not processed."));
	}
}
public function onlineusers(){
	if($this->input->is_ajax_request()){
	$uid = $this->input->post('my');
	$time = date("Y-m-d H:i:s",$this->input->post('time'));
	$this->load->model('message_model');
	$mythread = $this->message_model->getOnlineFriend($uid);
	if(count($mythread)>0){
	foreach($mythread as $threads){
		$threadid = $threads->thread_id;
		$checking = $this->db->query("select count(*) as cnt from tbl_message where thread_id='$threadid' and created_date>'$time' and flag_seen='0'");
		$this->db->query("UPDATE `tbl_message` SET `flag_seen`='1',`seen_on`=now() WHERE thread_id='$threadid' and created_date>'$time' and flag_seen='1'");
		$check = $checking->result_array();
		$cnt = $check[0]['cnt'];
		$newmsg=array();
		if($cnt>0){
			$userid = $threads->id;
			$newmsg[] = $userid;
		}
	}
	$data = array("online"=>$mythread,'newmsg'=>$newmsg);
	echo json_encode(array("status"=>200,"result"=>$data));exit;
	}else{
		echo json_encode(array("status"=>201,"result"=>"No online friends available."));exit;
	}
	}else{
		echo json_encode(array("status"=>501,"result"=>"This request not processed."));
	}
}
public function emptythread(){
	if($this->input->is_ajax_request()){
		$threads = $this->input->post('threads');
		$mine = $this->input->post('mine');
		if($threads!=='' && $mine!=""){
			$checking = $this->db->query("select * from tbl_message_thread where thread_id='$threads' and (sender_id = '$mine' or receiver_id = '$mine')");
			if($checking->num_rows()>0){
				$fetch = $this->db->query("select * from tbl_message where thread_id='$threads'");
				if($fetch->num_rows()>0){
				//$fetch5 = $this->db->query("update tbl_message set delete_status = '0' where thread_id='$threads' and delete_status<>'0'");
					 $data = array(
								 'delete_status' => '0'
								 );
					 $this->db->where('thread_id', $threads);
					 $this->db->where('delete_status <>', '0');
					 //$this->db->where('delete_status <>', '1');
					 $this->db->update('tbl_message', $data); 
					$l = $this->db->affected_rows();
				}
				//update it with my id
				$fetch1 = $this->db->query("select * from tbl_message where thread_id='$threads' and delete_status='0'");
				if($fetch1->num_rows()>0){
				//$fetch3 = $this->db->query("update tbl_message set delete_status = '9455678' where thread_id='$threads' and delete_status='0'");
				 $data = array(
								    'delete_status' => '9455678'
								 );
					 $this->db->where('thread_id', $threads);
					 $this->db->where('delete_status', '0');
					$this->db->update('tbl_message', $data);
					$m = $this->db->affected_rows();
				}
				
				echo json_encode(array("status"=>200,"result"=>"Message box cleared successfully.","my1" => $l,"my2" => $m));exit;
			}else{
				echo json_encode(array("status"=>201,"result"=>"Undefined user for this conversation."));exit;
			}
		}else{
		echo json_encode(array("status"=>201,"result"=>"Data is blank."));exit;
		}
	}else{
		echo json_encode(array("status"=>501,"result"=>"This request not processed."));
	}
}
	?>